package work.linruchang.util;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

/**
 * 增强的JSON工具类
 *
 * @author Administrator
 * @date 2023/10/15
 */
public class EnhanceJSONUtil extends JSONUtil {

    /**
     * 将实体转成携带类型名的Json字符串
     * @param obj
     * @return
     */
    @SneakyThrows
    public static String toJsonStrByRedis(Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        String json = objectMapper.writeValueAsString(obj);
        return json;
    }

    /**
     * 将携带类型名的Json字符串转换成Bean实体
     * @param json
     * @return
     * @param <T>
     */
    @SneakyThrows
    public static <T> T toBeanByRedis(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        T bean = (T) objectMapper.readValue(json, Object.class);


        return bean;
    }

}
